package cl.indumotora.induapprecepcion.app;

import java.io.ByteArrayOutputStream;
import java.io.File;

import cl.indumotora.induapprecepcion.db.ControladoraDB;
import cl.indumotora.induapprecepcion.modelo.Evento;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.provider.MediaStore.Images;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Spinner;

public class InspeccionVehiculoEvento extends Activity 
{
	Spinner cmbParteAuto;
	RadioGroup rdgDefecto;
	Button btnCamara;
	Button btnGuardarEvento;
	ControladoraDB db = new ControladoraDB();
	ImageView imgEvento;
	private static final int CAMERA_REQUEST = 1888; 
	String tipoFoto = "";
	Bitmap photo = null;
	EditText txtObservacionEvento;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_inspeccion_vehiculo_evento);
		
		ObtenerControles();
		
		Bundle extras = getIntent().getExtras(); 
		tipoFoto = extras.getString("TIPOFOTO");
		
		int tipo = 0;
		if(tipoFoto.equals("1")) tipo = R.array.array_auto_frontal;
		else if (tipoFoto.equals("2")) tipo = R.array.array_auto_izquierdo;
		else if (tipoFoto.equals("3")) tipo = R.array.array_auto_derecho;
		else if (tipoFoto.equals("4")) tipo = R.array.array_auto_trasero;
		
		ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this, tipo, android.R.layout.simple_spinner_item);
		adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		cmbParteAuto.setAdapter(adapter);
		     
		btnCamara.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE); 
                startActivityForResult(cameraIntent, CAMERA_REQUEST); 				
			}
		});
		
		btnGuardarEvento.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				Evento evento = new Evento();
				evento.setEventoInspeccionId(1);
				int selectedId = rdgDefecto.getCheckedRadioButtonId();
	            RadioButton rdDefecto = (RadioButton) findViewById(selectedId);
	            evento.setEventoDefecto(rdDefecto.getText().toString());
	            evento.setEventoParteAuto(cmbParteAuto.getSelectedItem().toString());
	            evento.setEventoRutaImagen(imgEvento.getTag().toString());
	            evento.setEventoZonaVehiculo(Integer.parseInt(tipoFoto));
	            evento.setEventoObservacion(txtObservacionEvento.getText().toString());
	            
	            System.out.println("EVENTO_INSPECCION_ID: " + evento.getEventoInspeccionId());
	            System.out.println("EVENTO_DEFECTO: " + evento.getEventoDefecto());
	            System.out.println("EVENTO_PARTE_AUTO: " + evento.getEventoParteAuto());
	            System.out.println("EVENTO_RUTA_IMAGEN: " + evento.getEventoRutaImagen());
	            System.out.println("EVENTO_OBSERVACION: " + evento.getEventoObservacion());
	            	           
	            InsertarEvento(evento);
	            
				finish();				
			}
		});
	}
	
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {  
        if (requestCode == CAMERA_REQUEST && resultCode == RESULT_OK) {  
            photo = (Bitmap) data.getExtras().get("data"); 
            imgEvento.setImageBitmap(photo);
            
            Uri tempUri = getImageUri(getApplicationContext(), photo);

            File finalFile = new File(getRealPathFromURI(tempUri));
            imgEvento.setTag(finalFile);
        }  
    } 
	
	@Override
	public void onConfigurationChanged(Configuration newConfig) {
	    super.onConfigurationChanged(newConfig);

	    if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) 
	    {
	        //NO EJECUTA NINGUN ACCION, Y NO PIERDE LA FOTO
	    } 
	    else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT)
	    {
	    	//NO EJECUTA NINGUNA ACCION, Y NO PIERDE LA FOTO
	    }
	}
	
	private void ObtenerControles()
	{
		cmbParteAuto = (Spinner)findViewById(R.id.cmbParteAuto);
		btnCamara = (Button)findViewById(R.id.btnFotoEvento);
		imgEvento = (ImageView)findViewById(R.id.imgImagenEvento);
		btnGuardarEvento = (Button)findViewById(R.id.btnGuardarEvento);
		rdgDefecto = (RadioGroup)findViewById(R.id.rdgGrupo);
		txtObservacionEvento = (EditText)findViewById(R.id.txtObservacionEvento);
	}
	
	public Uri getImageUri(Context inContext, Bitmap inImage) {
	    ByteArrayOutputStream bytes = new ByteArrayOutputStream();
	    inImage.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
	    String path = Images.Media.insertImage(inContext.getContentResolver(), inImage, "Title", null);
	    return Uri.parse(path);
	}

	public String getRealPathFromURI(Uri uri) {
	    Cursor cursor = getContentResolver().query(uri, null, null, null, null); 
	    cursor.moveToFirst(); 
	    int idx = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA); 
	    return cursor.getString(idx); 
	}
	
	private void InsertarEvento(Evento evento)
	{
		db.InsertarEvento(this, evento);
	}
}
